package com.company.OfferGuide;

import com.company.TreeNode;

import java.util.LinkedList;
import java.util.Queue;

public class 二叉树的深度 {

    public int maxDepth(TreeNode root) {
        int depth = 0;
        if (root == null) return depth;

        Queue<TreeNode> queue = new LinkedList<>();

        queue.offer(root);
        int nodeCount = 0,thisNodeCount = 1,nextNodeCount=0;

        while (!queue.isEmpty()) {
            TreeNode node = queue.poll();

            nodeCount++;

            if (node.left != null) {
                queue.offer(node.left);
                nextNodeCount++;
            }

            if (node.right != null) {
                queue.offer(node.right);
                nextNodeCount++;
            }

            if (nodeCount == thisNodeCount) {
                nodeCount = 0;
                thisNodeCount = nextNodeCount;
                nextNodeCount = 0;
                depth++;
            }
        }

        return depth;

    }

}
